package com.tebiecloud.order.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.mybatis.query.CriteriaQuery;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.DateUtils;
import com.tebiecloud.common.utils.DigitUtils;
import com.tebiecloud.order.client.model.entity.OrderWriteOffLog;
import com.tebiecloud.order.client.model.entity.Orderr;
import com.tebiecloud.order.server.service.OrderStats2Service;
import com.tebiecloud.order.server.service.OrderWriteOffLogService;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.order.server.service.feign.StoreStaffServiceClient;
import com.tebiecloud.store.client.constatns.StoreConstants;
import com.tebiecloud.store.client.model.entity.StoreStaff;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单核销记录 前端控制器
 * @author tebie
 * @date 2019-09-26
 */
@Slf4j
@RestController
@RequestMapping("/orderwriteofflog")
public class OrderWriteOffLogController {

    @Autowired
    OrderStats2Service orderStats2Service;

    @Autowired
    private OrderWriteOffLogService orderWriteOffLogService;

    @Autowired
    private StoreStaffServiceClient storeStaffServiceClient;

    /**
     * 门店核销记录
     * @param storeId
     * @return
     */
    @PostMapping(value = "listBlock")
    public ResultBody listBlock(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                @RequestParam(value = "limit", required = false, defaultValue = "10") int limit,
                                @RequestParam("storeId") long storeId) {

        // 查询条件
        CriteriaQuery criteriaQuery = new CriteriaQuery(new PageParams(page,limit));
        criteriaQuery.select("count(*) count", "sum(price) price", "DATE_FORMAT(ct, '%Y-%m-%d') date");
        criteriaQuery.eq("store_id", storeId);
        criteriaQuery.eq("pay_type",1);
        criteriaQuery.groupBy("DATE_FORMAT(ct, '%Y%m%d')");
        criteriaQuery.orderByDesc("ct");

        IPage<Map<String, Object>> pageList = orderWriteOffLogService.pageList(criteriaQuery);
        if(pageList.getRecords() != null && pageList.getRecords().size() > 0) {
            // 循环获取详细信息
            for(Map<String, Object> itemMap : pageList.getRecords()) {
                QueryWrapper<OrderWriteOffLog> queryWrapper = new QueryWrapper();
                queryWrapper.eq("store_id", storeId);
                queryWrapper.eq("pay_type",1);
                queryWrapper.ge("ct", itemMap.get("date"));
                queryWrapper.le("ct", itemMap.get("date") + " 23:59:59");
                queryWrapper.orderByDesc("ct");
                itemMap.put("listOrderWriteOffLog", orderWriteOffLogService.list(queryWrapper));
            }
        }
        return ResultBodyUtils.ok(pageList);
    }


    /**
     * 个人业绩
     * @param storeId
     * @return
     */
    @PostMapping(value = "listWriteOff")
    public ResultBody listWriteOff(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                @RequestParam(value = "limit", required = false, defaultValue = "10") int limit,
                                @RequestParam("storeId") long storeId) {
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        //查询用户门店角色
        StoreStaff storeStaff = null;
        ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(storeId,userId,null);
        if(storeStaffResultBody!=null && storeStaffResultBody.getCode() == ResultEnum.OK.getCode()){
            storeStaff = storeStaffResultBody.getData();
            if(storeStaff==null) return ResultBodyUtils.failed("查询所在门店角色不存在");
        }
        // 查询条件
        CriteriaQuery criteriaQuery = new CriteriaQuery(new PageParams(page,limit));
        criteriaQuery.select("count(*) count", "sum(price) price", "DATE_FORMAT(ct, '%Y-%m-%d') date");
        criteriaQuery.eq("store_id", storeId);
        criteriaQuery.eq("user_id", userId);
        criteriaQuery.groupBy("DATE_FORMAT(ct, '%Y%m%d')");
        criteriaQuery.orderByDesc("ct");

        IPage<Map<String, Object>> pageList = orderWriteOffLogService.pageList(criteriaQuery);
        if(pageList.getRecords() != null && pageList.getRecords().size() > 0) {
            // 循环获取详细信息
            for(Map<String, Object> itemMap : pageList.getRecords()) {
                QueryWrapper<OrderWriteOffLog> queryWrapper = new QueryWrapper();
                queryWrapper.eq("store_id", storeId);
                queryWrapper.eq("user_id", userId);
                queryWrapper.ge("ct", itemMap.get("date"));
                queryWrapper.le("ct", itemMap.get("date") + " 23:59:59");
                queryWrapper.orderByDesc("ct");
                itemMap.put("listOrderWriteOffLog", orderWriteOffLogService.list(queryWrapper));
            }
        }
        return ResultBodyUtils.ok(pageList);
    }

    /**
     * 统计上月，本月，今天业绩
     * @param storeId
     * @return
     */
    @PostMapping(value = "infoStats1")
    public ResultBody infoStats1(@RequestParam("storeId") long storeId) {
        Map<String, Object> map = Maps.newHashMap();

        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();

        // 提前获取相关时间
        String beforeMonth = DateUtils.formatDate(DateUtils.getBeforeMonth(new Date()), "yyyy-MM");
        String beforeMonthLastDay = DateUtils.getLastDayOfMonth(beforeMonth);
        String thisMonth = DateUtils.formatDate(new Date(), "yyyy-MM");
        String today = DateUtils.formatCurrentDate("yyyy-MM-dd");

        //获取用户信息
        map.put("name", "");
        map.put("headimgurl", "");
        map.put("phone", "");
        ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(storeId,userId,null);
        if(storeStaffResultBody!=null && storeStaffResultBody.getCode() == ResultEnum.OK.getCode()){
            StoreStaff storeStaff = storeStaffResultBody.getData();
            if(storeStaff!=null){
                map.put("name", storeStaff.getName());
                map.put("headimgurl", storeStaff.getHeadimgurl());
                map.put("phone", storeStaff.getPhone());
            }else {
                map.put("name", "");
                map.put("headimgurl", "");
                map.put("phone", "");
            }
        }
        // 上月业绩
        int lastMonthPrice = statsPrice(storeId, userId, beforeMonth + "-01 00:00:00", beforeMonthLastDay);
        map.put("lastMonthAmount", lastMonthPrice);

        // 本月业绩
        int thisMonthPrice = statsPrice(storeId, userId, thisMonth + "-01 00:00:00", today + " 23:59:59");
        map.put("thisMonthAmount", thisMonthPrice);

        // 今天业绩
        int todayPrice = statsPrice(storeId, userId, today + " 00:00:00", today + " 23:59:59");
        map.put("todayAmount", todayPrice);

        return ResultBodyUtils.ok(map);
    }

    /**
     * 统计价格
     * @param stime 起始时间
     * @param etime 结束时间
     * @return
     */
    private int statsPrice(long storeId, long userId, String stime, String etime) {
        QueryWrapper<OrderWriteOffLog> orderWriteOffLogQueryWrapper = new QueryWrapper<>();
        orderWriteOffLogQueryWrapper.select("sum(price) price");
        orderWriteOffLogQueryWrapper.eq("store_id", storeId);
        orderWriteOffLogQueryWrapper.eq("user_id", userId);
        orderWriteOffLogQueryWrapper.ge("ct", stime);
        orderWriteOffLogQueryWrapper.le("ct", etime);
        orderWriteOffLogQueryWrapper.groupBy("store_id");
        Map<String, Object> mapThisMonth = orderWriteOffLogService.getMap(orderWriteOffLogQueryWrapper);
        if(mapThisMonth != null) {
            return DigitUtils.obj2Int(mapThisMonth.get("price"), 0);
        }
        return 0;
    }

//    /**
//     * 根据ID查找数据
//     * @param id
//     * @return
//     */
//    @GetMapping("get")
//    public ResultBody<OrderWriteOffLog> get(@RequestParam("id") Long id) {
//        OrderWriteOffLog entity = orderWriteOffLogService.getById(id);
//        return ResultBodyUtils.ok(entity);
//    }
//
//    /**
//     * 添加数据
//     * @param orderGoodsId 订单商品id,
//     * @param storeId 门店id,
//     * @param userId 核销人id,
//     * @param userName 核销人名称,
//     * @param price 核销的订单费用（单位：分）,
//     * @param payType 支付类型：1微信支付，2现金支付，3刷卡支付,
//     * @param receiver 收货人,
//     * @param receiverHeadimgurl 收货人头像
//     * @return
//     */
//    @PostMapping("add")
//    public ResultBody add(
//        @RequestParam(value = "orderGoodsId", required = false) Long orderGoodsId,
//        @RequestParam(value = "storeId", required = false) Long storeId,
//        @RequestParam(value = "userId", required = false) Long userId,
//        @RequestParam(value = "userName", required = false) String userName,
//        @RequestParam(value = "price", required = false) Integer price,
//        @RequestParam(value = "payType", required = false) Integer payType,
//        @RequestParam(value = "receiver", required = false) String receiver,
//        @RequestParam(value = "receiverHeadimgurl", required = false) String receiverHeadimgurl
//    ) {
//        OrderWriteOffLog entity = new OrderWriteOffLog();
//        entity.setOrderGoodsId(orderGoodsId);
//        entity.setStoreId(storeId);
//        entity.setUserId(userId);
//        entity.setUserName(userName);
//        entity.setPrice(price);
//        entity.setPayType(payType);
//        entity.setReceiver(receiver);
//        entity.setReceiverHeadimgurl(receiverHeadimgurl);
//        orderWriteOffLogService.save(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 更新数据
//     * @param orderGoodsId 订单商品id
//     * @param storeId 门店id
//     * @param userId 核销人id
//     * @param userName 核销人名称
//     * @param price 核销的订单费用（单位：分）
//     * @param payType 支付类型：1微信支付，2现金支付，3刷卡支付
//     * @param receiver 收货人
//     * @param receiverHeadimgurl 收货人头像
//     * @return
//     */
//    @PostMapping("update")
//    public ResultBody update(
//            @RequestParam(value = "orderGoodsId", required = false) Long orderGoodsId,
//            @RequestParam(value = "storeId", required = false) Long storeId,
//            @RequestParam(value = "userId", required = false) Long userId,
//            @RequestParam(value = "userName", required = false) String userName,
//            @RequestParam(value = "price", required = false) Integer price,
//            @RequestParam(value = "payType", required = false) Integer payType,
//            @RequestParam(value = "receiver", required = false) String receiver,
//            @RequestParam(value = "receiverHeadimgurl", required = false) String receiverHeadimgurl
//    ) {
//        OrderWriteOffLog entity = new OrderWriteOffLog();
//        entity.setOrderGoodsId(orderGoodsId);
//        entity.setStoreId(storeId);
//        entity.setUserId(userId);
//        entity.setUserName(userName);
//        entity.setPrice(price);
//        entity.setPayType(payType);
//        entity.setReceiver(receiver);
//        entity.setReceiverHeadimgurl(receiverHeadimgurl);
//        orderWriteOffLogService.updateById(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 删除数据
//     * @param id 单个id
//     * @param ids 多个id用,号隔开
//     * @return
//     */
//    @PostMapping("remove")
//    public ResultBody remove(
//            @RequestParam(value = "id", required = false) Long id,
//            @RequestParam(value = "ids", required = false) String ids
//    ) {
//        if(id != null && id > 0) {
//            orderWriteOffLogService.removeById(id);
//        }
//        if(ids != null && ids.length() > 0) {
//            orderWriteOffLogService.removeByIds(Arrays.asList(ids.split(",")));
//        }
//        return ResultBodyUtils.ok();
//    }

}
